# 在项目根目录创建 utils 文件夹，新建 exceptions.py
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
import logging

# 配置日志（记录错误详情，便于部署后排查）
logger = logging.getLogger(__name__)


def custom_exception_handler(exc, context):
    # 1. 先调用DRF默认的异常处理（处理参数错误、权限错误等已知异常）
    response = exception_handler(exc, context)

    # 2. 处理DRF未捕获的未知异常（如数据库错误、代码bug）
    if response is None:
        if isinstance(exc, Exception):
            # 记录错误日志（包含请求路径、用户、错误详情）
            request = context.get('request')
            user = request.user.username if hasattr(request, 'user') and request.user.is_authenticated else '匿名用户'
            path = request.path if request else '未知路径'
            logger.error(f"未知异常 - 用户：{user}，路径：{path}，错误：{str(exc)}", exc_info=True)

            # 统一返回500错误格式
            return Response(
                {"code": 500, "msg": "服务器内部错误", "data": {}},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    # 3. 统一DRF已知异常的返回格式
    if response is not None:
        # 处理参数错误（400）
        if response.status_code == status.HTTP_400_BAD_REQUEST:
            return Response(
                {"code": 400, "msg": "参数错误", "data": response.data},
                status=status.HTTP_400_BAD_REQUEST
            )
        # 处理未登录/令牌失效（401）
        elif response.status_code == status.HTTP_401_UNAUTHORIZED:
            return Response(
                {"code": 401, "msg": "未登录或令牌失效", "data": {}},
                status=status.HTTP_401_UNAUTHORIZED
            )
        # 处理无权限（403）
        elif response.status_code == status.HTTP_403_FORBIDDEN:
            return Response(
                {"code": 403, "msg": "无操作权限", "data": {}},
                status=status.HTTP_403_FORBIDDEN
            )
        # 处理资源不存在（404）
        elif response.status_code == status.HTTP_404_NOT_FOUND:
            return Response(
                {"code": 404, "msg": "资源不存在", "data": {}},
                status=status.HTTP_404_NOT_FOUND
            )

    return response